import React, { useState } from 'react';
import { Card, Table, Button, Input, Select, Tag, Modal, Form, DatePicker, Switch, message } from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, FilterOutlined, ReloadOutlined } from '@ant-design/icons';

const { Option } = Select;
const { RangePicker } = DatePicker;

const UserManagement = () => {
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState('create'); // 'create' or 'edit'
  const [selectedUser, setSelectedUser] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [roleFilter, setRoleFilter] = useState('all');

  // 模拟角色数据
  const roles = [
    { id: '1', name: '管理员' },
    { id: '2', name: '运营人员' },
    { id: '3', name: '财务人员' },
    { id: '4', name: '客服人员' },
  ];

  // 模拟用户数据
  const [users, setUsers] = useState([
    {
      id: '1',
      username: 'admin',
      email: 'admin@example.com',
      phone: '13800138000',
      roleId: '1',
      roleName: '管理员',
      status: 'active',
      createTime: '2024-01-01 00:00:00',
      lastLogin: '2024-04-12 15:30:45',
    },
    {
      id: '2',
      username: 'marketing',
      email: 'marketing@example.com',
      phone: '13800138001',
      roleId: '2',
      roleName: '运营人员',
      status: 'active',
      createTime: '2024-01-10 10:30:00',
      lastLogin: '2024-04-11 14:20:30',
    },
    {
      id: '3',
      username: 'finance',
      email: 'finance@example.com',
      phone: '13800138002',
      roleId: '3',
      roleName: '财务人员',
      status: 'active',
      createTime: '2024-01-15 14:00:00',
      lastLogin: '2024-04-10 09:45:12',
    },
    {
      id: '4',
      username: 'customer',
      email: 'customer@example.com',
      phone: '13800138003',
      roleId: '4',
      roleName: '客服人员',
      status: 'inactive',
      createTime: '2024-02-01 09:00:00',
      lastLogin: '2024-02-15 16:20:00',
    },
  ]);

  // 表格列定义
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: (text) => <a href="#">{text}</a>,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'default'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '上次登录',
      dataIndex: 'lastLogin',
      key: 'lastLogin',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            style={{ marginRight: 8 }}
          >
            编辑
          </Button>
          {record.username !== 'admin' && (
            <Button
              type="text"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(record.id)}
            >
              删除
            </Button>
          )}
        </>
      ),
      width: 120,
    },
  ];

  // 过滤用户数据
  const filteredUsers = users.filter((user) => {
    const matchesSearch = user.username.toLowerCase().includes(searchText.toLowerCase()) ||
                         user.email.toLowerCase().includes(searchText.toLowerCase()) ||
                         user.phone.includes(searchText);
    const matchesStatus = statusFilter === 'all' || user.status === statusFilter;
    const matchesRole = roleFilter === 'all' || user.roleId === roleFilter;
    return matchesSearch && matchesStatus && matchesRole;
  });

  // 打开创建模态框
  const showCreateModal = () => {
    form.resetFields();
    setModalType('create');
    setIsModalVisible(true);
  };

  // 打开编辑模态框
  const handleEdit = (user) => {
    setSelectedUser(user);
    setModalType('edit');
    form.setFieldsValue({
      ...user,
    });
    setIsModalVisible(true);
  };

  // 删除用户
  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个用户吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setUsers(users.filter((user) => user.id !== id));
        message.success('用户已删除');
      },
    });
  };

  // 提交表单
  const handleSubmit = (values) => {
    if (modalType === 'create') {
      // 创建新用户
      const newUser = {
        id: Date.now().toString(),
        ...values,
        roleName: roles.find(role => role.id === values.roleId)?.name || '',
        createTime: new Date().toLocaleString('zh-CN'),
        lastLogin: '-',
      };
      setUsers([newUser, ...users]);
      message.success('用户创建成功');
    } else {
      // 编辑用户
      const updatedUsers = users.map((user) =>
        user.id === selectedUser.id
          ? {
              ...user,
              ...values,
              roleName: roles.find(role => role.id === values.roleId)?.name || '',
            }
          : user
      );
      setUsers(updatedUsers);
      message.success('用户更新成功');
    }
    setIsModalVisible(false);
  };

  // 刷新数据
  const handleRefresh = () => {
    // 这里应该调用API刷新数据，这里简化处理
    message.success('数据已刷新');
  };

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h2>用户管理</h2>
        <p style={{ color: '#8c8c8c' }}>管理系统用户、角色和权限</p>
      </div>

      <Card
        bordered={false}
        style={{ borderRadius: 8, marginBottom: 24 }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <div style={{ display: 'flex', gap: 16 }}>
            <div style={{ width: 200 }}>
              <Input
                placeholder="搜索用户名/邮箱/手机号"
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ borderRadius: 4 }}
              />
            </div>
            <Select
              placeholder="选择状态"
              value={statusFilter}
              onChange={setStatusFilter}
              style={{ width: 120 }}
              prefix={<FilterOutlined />}
            >
              <Option value="all">全部</Option>
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
            <Select
              placeholder="选择角色"
              value={roleFilter}
              onChange={setRoleFilter}
              style={{ width: 120 }}
              prefix={<FilterOutlined />}
            >
              <Option value="all">全部</Option>
              {roles.map((role) => (
                <Option key={role.id} value={role.id}>{role.name}</Option>
              ))}
            </Select>
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
            >
              刷新
            </Button>
          </div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={showCreateModal}
          >
            添加用户
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={filteredUsers}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          rowKey="id"
        />
      </Card>

      {/* 创建/编辑用户模态框 */}
      <Modal
        title={modalType === 'create' ? '创建用户' : '编辑用户'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          {modalType === 'create' && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="roleId"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="请选择角色">
              {roles.map((role) => (
                <Option key={role.id} value={role.id}>{role.name}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            valuePropName="checked"
            rules={[{ required: true }]}
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>

          <Form.Item style={{ textAlign: 'right' }}>
            <Button style={{ marginRight: 8 }} onClick={() => setIsModalVisible(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              {modalType === 'create' ? '创建' : '保存'}
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;